<?php

declare(strict_types=1);

namespace App\Common\Modular\Administer\Serve;

use App\Common\Modular\Administer\Model\MenuModel;
use Core\Basics\BasicsServe;
use Zms\Exception\AppException;
use Zms\Unit\Arr;

class MenuServe extends BasicsServe
{

    /**
     * @return MenuModel::class
     */
    public static function model(): string
    {
        return MenuModel::class;
    }


    /**
     * 添加后台菜单
     * @param array $values
     * @return null|MenuModel
     * @throws AppException
     */
    public function created(array $values): MenuModel|false
    {
        if (intval($values['pid']) > 0) {
            /**
             * @var MenuModel $parent
             */
            $parent = $this->search(['id' => $values['pid']])->first();
            if (!$parent) {
                throw new AppException('上级菜单不存在,请刷新后重试');
            }
            $values['group'] = Arr::join(Arr::push($parent['group'], $values['pid']), ',');
            $values['level'] = $parent['level'] + 1;
        } else {
            $values['level'] = 0;
        }
        return parent::created($values);
    }


    /**
     * 删除菜单
     */
    public function remove($id)
    {
        return $this->search("(FIND_IN_SET('$id',`group`) OR `id`='$id')")->delete();
    }
}